package com.dabai.sas.activitys;

import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import com.afollestad.materialdialogs.MaterialDialog;
import com.dabai.sas.R;
import com.dabai.sas.utils.DabaiUtils;
import com.dabai.sas.utils.FileUtil;
import com.dabai.sas.utils.KFileUtil;
import com.dabai.sas.utils.UriUtils;
import com.dabai.utils.FileLengthUtils;
import com.github.chrisbanes.photoview.PhotoView;
import com.tbruyelle.rxpermissions3.RxPermissions;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;

import static android.provider.SyncStateContract.Columns.DATA;

public class PhotoViewerActivity extends AppCompatActivity {

    Context context;
    PhotoView pv;
    String TAG = "DABAI";
    Uri uri;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_photo_viewer);

        pv = findViewById(R.id.photo_view);

        context = getApplicationContext();

        Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);

        RxPermissions rxPermissions = new RxPermissions(this);
        if (!rxPermissions.isGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            DabaiUtils.showToast(context, "请点击申请'储存权限'!");
            startActivity(new Intent(this, PermissionsActivity.class));
            finish();
            return;
        }


        pv.setOnClickListener(view -> {
            //Log.d(TAG, "onCreate: "+getSupportActionBar().isShowing());
            if (getSupportActionBar().isShowing()) {
                getSupportActionBar().hide();
                getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN);
                getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
            } else {
                getSupportActionBar().show();
                getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
            }
        });


        try {
            init();
        } catch (Exception e) {
            DabaiUtils.showToast(this, "图片打开失败!");
            finish();
        }

    }

    private void init() throws Exception {

        //拿到uri
        uri = getIntent().getData();

        pv.setImageURI(uri);

        if (uri.toString().startsWith("file:///")) {
            File file = new File(FileUtil.getFileAbsolutePath(this, uri));

            getSupportActionBar().setTitle(file.getName());
        } else {
            UriUtils file = new UriUtils(context, uri);
            getSupportActionBar().setTitle(file.getFileName());
        }

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.photo_viewer_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
            case R.id.more_detail:

                Bitmap bitmap = null;
                try {
                    bitmap = getBitmapFromUri(uri);
                } catch (IOException e) {
                    e.printStackTrace();
                }

                String path, name, size;

                if (uri.toString().startsWith("file:///")) {
                    File file = new File(FileUtil.getFileAbsolutePath(this, uri));
                    name = file.getName();
                    path = file.getAbsolutePath();
                    size = FileLengthUtils.FormetFileSize(file.length());
                } else {
                    UriUtils uriUtils = new UriUtils(context, uri);
                    name = uriUtils.getFileName();
                    path = uri.getPath();

                    String[] projection = {"_data", "_display_name", "_size", "mime_type", "title", "orientation"};
                    Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
                    cursor.moveToFirst();
                    size = FileLengthUtils.FormetFileSize(Long.parseLong(cursor.getString(cursor.getColumnIndex("_size"))));
                }

                String info = "文件名:" + name +
                        "\n文件路径:" + path +
                        "\n分辨率:" + bitmap.getWidth() + "x" + bitmap.getHeight() +
                        "\n大小:" + size;

                new MaterialDialog.Builder(this)
                        .backgroundColor(Color.DKGRAY)
                        .contentColor(Color.WHITE)
                        .titleColor(Color.WHITE)
                        .title("详细信息")
                        .content(info)
                        .positiveText("确认")
                        .show();

                return true;
            case R.id.share:
                DabaiUtils.sendFileWithUri(this, uri, "image/*");
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    private Bitmap getBitmapFromUri(Uri uri) throws IOException {
        ParcelFileDescriptor parcelFileDescriptor =
                getContentResolver().openFileDescriptor(uri, "r");
        FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
        Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
        parcelFileDescriptor.close();
        return image;
    }


}